package com.open.capacity.finance.controller;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.open.capacity.commons.Result;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.access.prepost.PreAuthorize;
import com.open.capacity.finance.entity.AuditModelRule;
import com.open.capacity.finance.service.AuditModelRuleService;

import com.open.capacity.commons.PageResult;

import javax.validation.Valid;

/**
 * 审计模型预警规则
 *
 * @author
 * @email
 * @date 2023-02-01 11:48:18
 */
@RestController
@RequestMapping("auditmodelrules")
@Api(tags = "审计模型预警规则")
public class AuditModelRuleController {

    @Autowired
    private AuditModelRuleService auditModelRuleService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @PreAuthorize("hasAnyAuthority('audit_model_rule:auditmodelrule:list')")
    public PageResult list(@RequestParam Map<String, Object> params) {
        PageResult pageResult = auditModelRuleService.pageAll(params);
        return pageResult;
    }

    /**
     * 查询单条记录
     */
    @RequestMapping("/findByModelId")
    @PreAuthorize("hasAnyAuthority('audit_model_rule:auditmodelrule:list')")
    public Result findByModelId(String modelId) {
        return Result.succeed(auditModelRuleService.findByModelId(modelId));
    }

    /**
     * 保存
     */
    @RequestMapping("/saveOrUpdate")
    @PreAuthorize("hasAnyAuthority('audit_model_rule:auditmodelrule:save')")
    public Result save(@RequestBody @Valid LinkedHashMap<String, String> linkedHashMap, String keyValue) {
        String modelId = linkedHashMap.entrySet().stream().filter(t -> t.getKey().equals("modelId")).findFirst().get().getValue();
        for (Map.Entry<String, String> entry : linkedHashMap.entrySet()) {
            String confKey = entry.getKey();
            if (confKey.equals("modelId") || confKey.equals("modelName")) {
                continue;
            }
            String confValue = entry.getValue();
            AuditModelRule model = auditModelRuleService.findByConfKey(modelId, confKey);
            model.setConfValue(confValue);
            auditModelRuleService.update(model);
        }
        return Result.succeed("保存成功");
    }


    /**
     * 删除
     */
    @RequestMapping("/delete/{id}")
    @PreAuthorize("hasAnyAuthority('audit_model_rule:auditmodelrule:delete')")
    public Result delete(@PathVariable String id) {
        auditModelRuleService.delete(id);
        return Result.succeed("删除成功");
    }
}
